import { Vec3 } from "cc";
import { BaseEventName, LoadingProcess } from "../../framework/config/Appcfg";
import { EventMgr } from "../../framework/manager/EventMgr";
import { EventName, GameConfig } from "../config/Config";
import { GuideData } from "../datas/GuideData";
import { ShareData } from "../datas/ShareData";
import { UserData } from "../datas/UserData";

export enum ABTestType {//AB测试
    /**无AB测试 */
    NO_AB,
    /**AB测试 */
    AB_Test,
    /**ABD测试 */
    ABD_Test,
    /**固定A */
    A_fixed,
    /**固定B */
    B_fixed,
    /**固定D */
    D_fixed,
}
export class PlayerMgr {

    private static _instance: PlayerMgr;
    isFirstTime: boolean = true;
    private constructor() { }
    public static getInstance(): PlayerMgr {
        if (this._instance == null) {
            this._instance = new PlayerMgr();
            this._instance.initData();
        }
        return this._instance;
    }

    public static get instance(): PlayerMgr {
        return this.getInstance();
    }
    ConifgName = ""
    private isLoaded: boolean = false;
    private udata: UserData;
    private shareData: ShareData;

    public uid = '';

    public appid = 'wx3b0cd3b2314f4770';

    public openid = 'oS2Mh7YZRdNl8p1_ck4mjwWqLZ3E'

    public token = '2bc55cf037a648a0bdcb6697a1b99e73';

    /**全部的花池 */
    private allFlowerGroup: number[][] = []

    /**自然恢复 */
    public timeAdd: number = 0
    /**金币回复体力 */
    public moneyAdd: number = 0
    /**广告回复 */
    public adAdd: number = 0
    /**是否可以存档 */
    public isCanSave = false;
    private initData() {

    }
    public userCloudData: any;

    public guideData: GuideData;
    preload() {
        if (this.isLoaded) {
            return;
        }
        console.log("玩家数据", this.uid)
        this.timeAdd = 5//DataMgr.getInstance().getItemCfgById(1).timeAdd
        this.moneyAdd = 1;//DataMgr.getInstance().getItemCfgById(1).buyAdd
        this.adAdd = 1;//DataMgr.getInstance().getItemCfgById(1).adAdd
        this.isLoaded = true;
        //用户数据
        this.udata = new UserData();
        this.udata.getData();
        //分享
        this.shareData = new ShareData();
        this.shareData.getData();
        
        this.guideData = new GuideData() 
        this.guideData.getData();
        EventMgr.getInstance().emit(BaseEventName.Loading, LoadingProcess.PlayerCfg)
    }

    getUserData(): UserData {
        return this.udata;
    }
    getShareData(): ShareData {
        return this.shareData;
    }
    get userData() {
        return this.udata;
    }


    /**添加奖励 */
    addRewards(reward: string, multe: number = 1, pos?: Vec3) {
        let rewards = reward.split(GameConfig.splitCount)
        for (let i = 0; i < rewards.length; i++) {
            if (rewards[i].length <= 0) {
                continue
            }
            let rewardcfg = rewards[i].split(GameConfig.splitNum);
            let goodsId = Number(rewardcfg[0])
            let num = Number(rewardcfg[1]) * multe
            //具体添加的方法
        }
    }
    clearFlowerLst() {
        this.allFlowerGroup = []
    }
    cnoleAllFlower;

    /**获取全部花池 */
    getAllFlower(): number[][] {
        return this.allFlowerGroup
    }
    private _cobwebsId = [];
    /**保存有蜘蛛网的花id */
    setHasCobwebsId(flowerId: number | number[] | null) {
        if (this._cobwebsId == null) {
            this._cobwebsId = []
        }
        if (!flowerId) {
            this._cobwebsId = []
            return;
        }
        if (Array.isArray(flowerId)) {
            this._cobwebsId.push(...flowerId)
            return
        }

        this._cobwebsId.push(flowerId)
    }
    /**获取有蜘蛛网的花id */
    get cobwebsId(): number[] {
        return this._cobwebsId
    }
    poolCobwebsId: number[] = []
    /**获取 */
    getFlowerData(): number[] {
        if (this.allFlowerGroup.length > 0) {
            return this.allFlowerGroup[0]
        } else {
            return [-1, -1, -1]
        }
    }
    /**设置 */
    setFlowerData(flowerG: number[], isShift: boolean = false) {

        if (isShift) {
            this.allFlowerGroup.shift()
            // console.warn("len", this.allFlowerGroup.length)

        } else {
            this.allFlowerGroup.push(flowerG)
        }


    }


    /**设置顶部 */
    setTopFlowerData(flowerG: number[], isShift: boolean = false) {

        this.allFlowerGroup.unshift(flowerG)
    }
    /**删除 */
    removeGroup(spliceId: number) {
        this.allFlowerGroup.splice(spliceId, 1)
    }
    /**根据id消除某种花 */
    removeFlowerByID(Fid: number) {
        let indexesToDelete: number = -1

        // 遍历每个子数组
        for (let i = 0; i < this.allFlowerGroup.length; i++) {
            let subArray = this.allFlowerGroup[i];
            let allReplaced = true;

            // 检查子数组中的每个元素
            for (let j = 0; j < subArray.length; j++) {
                if (subArray[j] === Fid) {
                    // 如果找到了目标值，将其替换为-1
                    subArray[j] = -1;
                } else {
                    allReplaced = false;
                }
            }

            // 如果子数组中的所有元素都被替换成了-1，则记录索引以待删除
            if (allReplaced) {
                indexesToDelete = i
                this.allFlowerGroup.splice(indexesToDelete, 1)

            }
        }
        console.log("this.allFlowerGroup", this.allFlowerGroup)
    }
    /**
     *  获取段位
     * @param index 0-青铜 1-白银 2-黄金
     * @returns boolean true-未解锁 false-解锁
     */
    unlockLevel(index: number) {
        return this.userData.getUnlockRank(index)
    }
    /**
     * 解锁段位
     * @param index 0-青铜 1-白银 2-黄金
     */
    setUnlockLevel(index: number) {
        this.userData.setUnlockRank(index)
    }

    // 新增每日重置检查
    public checkDailyReset() {
        const now = Math.floor(Date.now() / 1000); // 当前时间戳;
        // 跨天重置
        if (now >= this.userData.data.unlimitedHpEndTime && this.userData.data.unlimitedHpEndTime > 0) {
            this.userData.data.videoWatchedCount = 0;
            this.userData.data.unlimitedHpEndTime = 0;
            this.saveData()
        }
        EventMgr.getInstance().emit(EventName.UnlimitedHp, this.isUnlimitedHp(), this.userData.data.videoWatchedCount || 0)
    }
    /** 增加观看视频次数 */
    public incrementVideoWatched() {
        if (this.isUnlimitedHp()) {
            return; // 无限体力状态下不增加次数 
        }
        this.userData.data.videoWatchedCount++;
        if (this.userData.data.videoWatchedCount == 3) {
            const now = new Date();
            // 设置次日同一时间过期
            this.userData.data.unlimitedHpEndTime = Math.floor(now.setDate(now.getDate() + 1) / 1000);
            EventMgr.getInstance().emit(EventName.UnlimitedHp, this.isUnlimitedHp(), this.userData.data.videoWatchedCount)
        }
        this.saveData()
    }
    public isUnlimitedHp(): boolean {
        return this.userData.data.unlimitedHpEndTime > Math.floor(Date.now() / 1000);
    }
    protected saveData() {
        this.userData.saveDataToLocad()
    }
    public get isMaxHp(): boolean {
        return this.userData.data.roleHp >= this.userData.data.maxRoleHp;
    }
    public reSetAddHpTimer() {
        this.userData.data.addHpEndTime = 600;
        this.saveData()
    }

    public getSkillCount(skillId: number): number {
        switch (skillId) {
            case 1: // 加速
                return this.userData.data.skill1;
            case 2: // 减速
                return this.userData.data.skill2
            case 3: // 无敌;
                return this.userData.data.skill3
        }
    }
    public setSkillCount(skillId: number, count: number=1) {
        switch (skillId) {
            case 1: // 加速
                this.userData.data.skill1 += count;
                break; 
            case 2: // 减速
                this.userData.data.skill2 += count;
                break;
            case 3: // 无敌;
                this.userData.data.skill3 += count;
                break;
        } 
        this.saveData()
    }

    public get isNewGuide(){
        return !this.getGuideData().isGuideEnd()
    }
    public setIsNewGuide(isNewGuide:boolean){
        // this.userData.data.isNewGuide = isNewGuide;
        // this.saveData() 
    }
    /**
     * 获取引导数据
     * @returns GuideData
     */
    public getGuideData(){
        return this.guideData;
    }
}
